package com.example.fastdfsdemo.interceptor;

import com.example.fastdfsdemo.config.StaticProperties;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 文件类型拦截器(demo主要拦截图片类型)
 * @author liuwenlin
 * @version v1.0
 * @date 2021/3/11 22:10
 */
public class FileTypeInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(FileTypeInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("logger进入文件拦截>>>");
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        //循环获取文件数据并进行判断，如有类型不匹配返回false
        for(Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){
            //获取单个文件
            MultipartFile file = entry.getValue();
            //获取文件的扩展名
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            logger.info("文件后缀名符合条件,不拦截>>>");
            if(this.checkFile(extension) == false){
                logger.info("文件后缀名不符合条件,进行拦截!");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 拦截器文件后缀名过滤处理
     * @param extension
     * @return
     */
    private  boolean checkFile(String extension){
        String suffixList = StaticProperties.suffixList;
        if(suffixList.contains(extension.trim().toLowerCase())){
            return true;
        }
        return false;
    }
}
